<?php

namespace App\Blocks;

use App\Models\Crowd;
use App\Models\CrowdMember;
use App\Models\Topic;
use App\Models\TopicComment;
use App\Models\TopicImgs;
use App\Models\TopicUsefulLog;
use App\Models\Users;
use DB;
use phpDocumentor\Reflection\Types\Null_;

class TopicBlock
{

    public function getTopicList($uid, $page = 1, $pageSize = 20)
    {
        $userModel = new Users();
        $topicModel = new Topic();
        $topicImgModel = new TopicImgs();
        $topicCommentModel = new TopicComment();
        $topicUserfulLogModel = new TopicUsefulLog();
        $crowdModel = new Crowd();

        $userIds = DB::table($userModel->getTable())->pluck('id');
        $sql = DB::table($topicModel->getTable() . ' as t')
            ->select(
                't.id',
                't.crowd_id',
                'c.name as crowd_name',
                't.uid',
                't.content',
                't.comment',
                't.created_at',
                'u.nick_name',
                'u.grade',
                'u.headimgurl'
            )
            ->leftJoin($userModel->getTable() . ' as u', 'u.id', '=', 't.uid')
            ->leftJoin($crowdModel->getTable() . ' as c', 'c.id', '=', 't.crowd_id')
            ->whereIn('t.uid',$userIds);

        $topics = $sql->whereNull('t.deleted_at')
            ->orderBy('t.created_at', 'desc')
            ->groupBy('t.id')
            ->skip(($page - 1) * $pageSize)->take($pageSize)
            ->get();

        $topicIds = [];
        foreach ($topics as $topic) {
            $topicIds[] = $topic->id;
        }

        $topicImgs = DB::table($topicImgModel->getTable())
            ->whereIn('topic_id', $topicIds)
            ->whereNull('deleted_at')
            ->get();

        $topicComment = DB::table($topicCommentModel->getTable() . ' as tm')
            ->select('tm.*', 'u.nick_name')
            ->leftJoin($userModel->getTable() . ' as u', 'u.id', '=', 'tm.user_id')
            ->whereIN('tm.topic_id', $topicIds)
            ->whereNull('tm.deleted_at')
            ->get();

        $topicUsefulCentent = DB::table($topicUserfulLogModel->getTable().' as tu')
            ->select('tu.topic_id','tu.user_id','tu.updated_at','u.nick_name')
            ->leftJoin($userModel->getTable().' as u','tu.user_id','=','u.id')
            ->whereIn('topic_id', $topicIds)
            ->whereNull('tu.deleted_at')
            ->get();

        $is_Useful = DB::table($topicUserfulLogModel->getTable())->select('topic_id')
            ->where('user_id',$uid)->whereNull('deleted_at')
            ->get();

        foreach ($topics as $topic) {
            $topic->imgs = [];
            $topic->comment_content = [];
            $topic->UsefulCentent = [];


            foreach ($topicImgs as $img) {
                if ($topic->id === $img->topic_id) {
                    $topic->imgs[] = $img;
                }
            }

            foreach ($topicComment as $Comments) {
                if ($topic->id === $Comments->topic_id) {
                    $topic->comment_content[] = $Comments;
                }
            }

            foreach ($topicUsefulCentent as $Usefuls) {
                if ($topic->id === $Usefuls->topic_id) {
                    $topic->UsefulCentent[] = $Usefuls;
                }
            }
        }
        $is_Useful = json_decode(json_encode($is_Useful),true);
        $Useful = [];
        foreach ($is_Useful as $useful){
            $Useful[] = $useful['topic_id'];
        }
        foreach ($topics as $val){
            if (!$is_Useful){
                $val->useful = 0;
            }else{

                if (in_array($val->id,$Useful)){
                    $val->useful = 1;
                }else{
                    $val->useful = 0;
                }

            }


        }

        return $topics;
    }

    //添加评论信息
    public function createTopic($data)
    {
        $topicModel = new Topic();
        $topicImgModel = new TopicImgs();
        try {
            $topicId = DB::table($topicModel->getTable())->insertGetId([
                'uid' => $data['uid'],
                'crowd_id' => $data['crowd_id'],
                'content' => $data['content'],
                'created_at' => date('Y-m-d H:i:s', time())
            ]);
            if ($topicId === false) {
                return false;
            }

            if ($data['img'] and is_array($data['img'])) {
                $imgData = [];
                foreach ($data['img'] as $img) {
                    $imgData[] = [
                        'topic_id' => $topicId,
                        'imgurl' => $img,
                        'created_at' => date('Y-m-d H:i:s', time())
                    ];
                }

                if (DB::table($topicImgModel->getTable())->insert($imgData) === false) {
                    DB::rollBack();
                    return false;
                }
            }

            DB::commit();
            return $topicId;
        } catch (\Exception $exception) {
            DB::rollBack();
            \Log::error($exception);
            return false;
        }
    }


    public function getTopicInfo($id)
    {
        $topicModel = new Topic();
        $topicImgModel = new TopicImgs();
        $commentModel = new TopicComment();
        $usefulModel = new TopicUsefulLog();
        $userModel = new Users();
        $crowdModel = new Crowd();
        $topic = DB::table($topicModel->getTable() . ' as t')
            ->select(
                't.id',
                't.uid',
                't.crowd_id',
                'c.name as crowd_name',
                't.content',
                't.created_at',
                'u.nick_name',
                'u.headimgurl'
            )
            ->leftJoin($userModel->getTable() . ' as u', 'u.id', '=', 't.uid')
            ->leftJoin($crowdModel->getTable() . ' as c', 'c.id', '=', 't.crowd_id')
            ->where('t.id', $id)
            ->whereNull('t.deleted_at')
            ->first();

        $imgs = DB::table($topicImgModel->getTable())->where('topic_id', $id)
            ->whereNull('deleted_at')
            ->get();

        $comment = DB::table($commentModel->getTable() . ' as tc')->where('topic_id',$id)
            ->select(
                'tc.*',
                'u.nick_name',
                'u.headimgurl'
            )
            ->leftJoin($userModel->getTable() . ' as u', 'u.id', '=', 'tc.user_id')
            ->whereNull('tc.deleted_at')
            ->get();

        $useful = DB::table($usefulModel->getTable())->where('topic_id',$id)
            ->whereNull('deleted_at')
            ->get();

        $topic->imgs = $imgs?$imgs:[];
        $topic->comment_content = $comment?$comment:[];
        $topic->UsefulCentent = $useful?$useful:[];
        return $topic;
    }

    public function getTopicComment($search = [], $page = 0, $pageSize = 20)
    {
        $topicCommentModel = new TopicComment();
        $userModel = new Users();
        $crowdMemberModel = new CrowdMember();
        $topicModel = new Topic();

        $sql = DB::table($topicCommentModel->getTable() . ' as tc')
            ->select(
                'tc.topic_id',
                'tc.user_id',
                'tc.content',
                'tc.created_at',
                'tc.updated_at',
                'u.nick_name',
                'u.headimgurl',
                'u.grade',
                'cm.active'
            )
            ->leftJoin($userModel->getTable() . ' as u', 'tc.user_id', '=', 'u.id')
            ->leftJoin($topicModel->getTable() . ' as t', 't.id', '=', 'tc.topic_id')
            ->leftJoin($crowdMemberModel->getTable() . ' as cm', function ($join) {
                $join->on('tc.user_id', '=', 'cm.user_id')
                    ->on('t.crowd_id', '=', 'cm.crowd_id');
            })
            ->whereNull('tc.deleted_at');
        if (isset($search['topic_id'])) {
            $sql->where('topic_id', $search['topic_id']);
        }
        if (isset($search['user_id'])) {
            $sql->where('user_id', $search['user_id']);
        }

        $comment = $sql->orderBy('tc.updated_at', 'desc')
            ->take(($page - 1) * $pageSize)->take($pageSize)
            ->get();

        return $comment;
    }


    public function getJoinCrowdTopicList($search = [], $page = 1, $pageSize = 20)
    {
        $userModel = new Users();
        $topicModel = new Topic();
        $topicImgModel = new TopicImgs();
        $crowdMemberModel = new CrowdMember();

        $sql = DB::table($crowdMemberModel->getTable() . ' as cm')
            ->select(
                't.id',
                't.crowd_id',
                't.uid',
                't.content',
                't.useful',
                't.comment',
                't.created_at',
                'u.nick_name',
                'u.grade',
                'u.headimgurl',
                'cm.active'
            )
            ->leftJoin($topicModel->getTable() . ' as t', 'cm.crowd_id', '=', 't.crowd_id')
            ->leftJoin($userModel->getTable() . ' as u', 'u.id', '=', 't.uid');

        if (isset($search['crowd_id'])) {
            $sql->where('t.crowd_id', $search['crowd_id']);
        }

        if (isset($search['user_id'])) {
            $sql->where('cm.user_id', $search['user_id']);
        }

        $topics = $sql->whereNull('t.deleted_at')
            ->orderBy('t.created_at', 'desc')
            ->skip(($page - 1) * $pageSize)->take($pageSize)
            ->get();

        $topicIds = [];
        foreach ($topics as $topic) {
            $topicIds[] = $topic->id;
        }

        $topicImgs = DB::table($topicImgModel->getTable())
            ->whereIn('topic_id', $topicIds)
            ->whereNull('deleted_at')
            ->get();
        foreach ($topics as $topic) {
            $topic->imgs = [];
            foreach ($topicImgs as $img) {
                if ($topic->id === $img->topic_id) {
                    $topic->imgs[] = $img;
                }
            }
        }

        return $topics;
    }


    //点赞
    public function useful($userId, $topicId)
    {


        try {
            DB::beginTransaction();
            $usefulModel = new TopicUsefulLog();
            $topicModel = new Topic();
            $userModel = new Users();
            $is_useful = DB::table($usefulModel->getTable())
                ->where('topic_id',$topicId)
                ->where('user_id',$userId)
                ->first();
            if ($is_useful){

                $inLog = DB::table($usefulModel->getTable())
                    ->where('topic_id',$topicId)
                    ->where('user_id',$userId)
                    ->update([
                        'deleted_at' => Null,
                        'unread' => 1
                ]);
            }else{
                $inLog = DB::table($usefulModel->getTable())->insertGetId([
                    'user_id' => $userId,
                    'topic_id' => $topicId
                ]);
            }

            if ($inLog=== false) {
                DB::rollBack();
                return false;
            }

            if (DB::table($topicModel->getTable())->where('id', $topicId)->update([
                    'useful' => DB::raw('useful + 1'),
                    'u_message'  => DB::raw('u_message + 1')]) === false) {
                DB::rollBack();
                return false;
            }

            DB::commit();
            $data = DB::table($usefulModel->getTable().' as uf')
                ->select('uf.topic_id','uf.user_id','uf.updated_at','u.nick_name')
                ->leftJoin($userModel->getTable().' as u','uf.user_id','=','u.id')
                ->where('user_id',$userId)
                ->where('topic_id',$topicId)
                ->first();
            return $data;
        } catch (\Exception $exception) {
            DB::rollBack();
            \Log::error($exception);
            return false;
        }
    }

    //取消点赞
    public function cancelUseful($userId,$topicId){
        try {
            DB::beginTransaction();
            $usefulModel = new TopicUsefulLog();
            $topicModel = new Topic();

            if (DB::table($usefulModel->getTable())
                    ->where('topic_id',$topicId)
                    ->where('user_id',$userId)
                    ->update(['deleted_at'=>date('Y-m-d',time())]) === false) {
                return false;
            }

            if (DB::table($topicModel->getTable())->where('id', $topicId)->decrement('useful') === false) {
                DB::rollBack();
                return false;
            }

            DB::commit();
            return $userId;
        } catch (\Exception $exception) {
            DB::rollBack();
            \Log::error($exception);
            return false;
        }
    }

    //动态评论
    public function createComment($userId,$topicId,$content){

        try {
            DB::beginTransaction();
            $topicCommentModel = new TopicComment();
            $topicModel = new Topic();
            $userModel = new Users();

            $addId = DB::table($topicCommentModel->getTable())->insertGetId([
                'user_id' => $userId,
                'topic_id' => $topicId,
                'content' => $content,
                'created_at' => date('Y-m-d H:i:s',time())
            ]);
            if (!$addId){
                return false;
            }

            if (DB::table($topicModel->getTable())->where('id', $topicId)->update([
                    'comment' => DB::raw('comment + 1'),
                    'c_message'  => DB::raw('c_message + 1')]) === false) {
                DB::rollBack();
                return false;
            }

            DB::commit();
            $res = DB::table($topicCommentModel->getTable().' as tc')
                ->select('tc.*','u.nick_name','u.headimgurl')
                ->leftJoin($userModel->getTable().' as u','tc.user_id','=','u.id')
                ->where('tc.id',$addId)
                ->first();
            if ($res){
                return $res;
            }
            return false;
        } catch (\Exception $exception) {
            DB::rollBack();
            \Log::error($exception);
            return false;
        }
    }


    //我的动态列表
    public function myTopic($uid){
        $topicModel = new Topic();
        $CommentModel = new TopicComment();
        $UsefulModel = new TopicUsefulLog();
        $UserModel = new Users();
        $ImgModel = new TopicImgs();

        $topicData = DB::table($topicModel->getTable().' as t')
            ->select('t.id','t.uid','u.nick_name','u.headimgurl','t.content','t.created_at')
            ->leftJoin($UserModel->getTable().' as u','t.uid','=','u.id')
            ->where('t.uid',$uid)
            ->whereNull('t.deleted_at')
            ->orderBy('created_at','desc')
            ->get();
        $topicId = [];
        foreach ($topicData as $topicDatum) {
            $topicId[] = $topicDatum->id;
        }


        $topicImgData = DB::table($ImgModel->getTable())
            ->select('id','topic_id','imgurl')
            ->whereIn('topic_id',$topicId)
            ->get();
        if (!$topicImgData){
            $topicImgData = [];
        }


        $commentData = DB::table($CommentModel->getTable().' as c')
            ->select('c.*','u.nick_name')
            ->leftJoin($UserModel->getTable().' as u','c.user_id','=','u.id')
            ->whereIn('topic_id',$topicId)
            ->orderBy('created_at','desc')
            ->get();
        if (!$topicImgData){
            $commentData = [];
        }



        $usefulData = DB::table($UsefulModel->getTable().' as f')
            ->select('f.*','u.nick_name')
            ->leftJoin($UserModel->getTable().' as u','f.user_id','=','u.id')
            ->whereIn('f.topic_id',$topicId)
            ->get();
        if (!$topicImgData){
            $usefulData = [];
        }

        foreach ($topicData as $datas) {

            $datas->imgs = [];
            foreach ($topicImgData as $topicImgDatum) {
                if ($datas->id == $topicImgDatum->topic_id){
                    $datas->imgs[] = $topicImgDatum;
                }
            }

            $datas->comment_content = [];
            foreach ($commentData as $commentDatum) {
                if ($datas->id == $commentDatum->topic_id){
                    $datas->comment_content[] = $commentDatum;
                }
            }

            $datas->UsefulCentent = [];
            foreach ($usefulData as $usefulDatum) {
                if ($datas->id == $usefulDatum->topic_id){
                    $datas->UsefulCentent[] = $usefulDatum;
                }
            }

        }

        return $topicData;
    }

    //未读消息
    public function unread($uid){
        $topicModel = new Topic();
        $UserModel = new Users();
        $CommentModel = new TopicComment();
        $UsefulModel = new TopicUsefulLog();

        $topicData = DB::table($topicModel->getTable())->select('id',DB::raw('sum(c_message+u_message) as message'))
            ->where('uid',$uid)
            ->whereNull('deleted_at')
            ->groupBy('id')
            ->get();
        if (count($topicData)<1){
            return ['message'=>0];
        }
        $message = 0;

        foreach ($topicData as $topicDatum) {
            if ($topicDatum->message > 0 ){
                $unreadId = $topicDatum->id;
            }
            $message = $topicDatum->message + $message;
        }
        if ($message<1){
            return ['message'=>0];
        }
        if ($message>99){
            $message = '99+';
        }

        $userId = DB::table($UsefulModel->getTable())
            ->select('user_id')
            ->where('topic_id',$unreadId)->whereNull('deleted_at')->first();
        if (!$userId){
            $userId = DB::table($CommentModel->getTable())
                ->select('user_id')
                ->where('topic_id',$unreadId)->whereNull('deleted_at')->first();
        }

        $headImg = DB::table($UserModel->getTable())->select('headimgurl')->where('id',$userId->user_id)->first();

        return ['message'=>$message,'headImg'=>$headImg->headimgurl];
    }

    //未读消息列表
    public function unreadList($uid){
        $topicModel = new Topic();
        $CommentModel = new TopicComment();
        $UsefulModel = new TopicUsefulLog();
        $UserModel = new Users();
        $ImgModel = new TopicImgs();

        $topicData = DB::table($topicModel->getTable().' as t')
            ->select(
                't.id',
                't.uid',
                'u.nick_name',
                'u.headimgurl',
                't.content',
                't.created_at',
                't.c_message',
                'u_message'
            )
            ->leftJoin($UserModel->getTable().' as u','t.uid','=','u.id')
            ->where('t.uid',$uid)
            ->whereNull('t.deleted_at')
            ->get();

        if (count($topicData)<1){
            return [];
        }

        foreach ($topicData as $topicDatum) {
            $topicId[] = $topicDatum->id;
        }

        $topicImgData = DB::table($ImgModel->getTable())
            ->select('id','topic_id','imgurl')
            ->whereIn('topic_id',$topicId)
            ->whereNull('deleted_at')
            ->get();

        $commentData = DB::table($CommentModel->getTable().' as c')
            ->select('c.id','c.topic_id','c.user_id','c.content','c.created_at','u.nick_name','u.headimgurl')
            ->leftJoin($UserModel->getTable().' as u','c.user_id','=','u.id')
            ->whereIn('c.topic_id',$topicId)
            ->whereNull('c.deleted_at')
            ->orderBy('created_at','desc')
            ->get();

        $usefulData = DB::table($UsefulModel->getTable().' as f')
            ->select('f.id','f.user_id','f.topic_id','f.updated_at','u.nick_name')
            ->leftJoin($UserModel->getTable().' as u','f.user_id','=','u.id')
            ->whereNull('f.deleted_at')
            ->whereIn('f.topic_id',$topicId)
            ->orderBy('updated_at','desc')
            ->get();

        foreach ($topicData as $topicDatum) {
            $topicDatum->imgs = [];
            foreach ($topicImgData as $topicImgDatum) {
                if ($topicDatum->id == $topicImgDatum->topic_id){
                    $topicDatum->imgs[] = $topicImgDatum;
                }
            }

            $topicDatum->comment_content = [];
            foreach ($commentData as $commentDatum) {
                if ($topicDatum->id == $commentDatum->topic_id){
                    $topicDatum->comment_content[] = $commentDatum;
                    $commId[] = $commentDatum->id;
                }
            }

            $topicDatum->UsefulCentent = [];
            foreach ($usefulData as $usefulDatum) {
                if ($usefulDatum->topic_id == $topicDatum->id){
                    $topicDatum->UsefulCentent[] = $usefulDatum;
                    $usefulId[] = $usefulDatum->id;
                }
            }
        }

        $topUpdate = DB::table($topicModel->getTable())->whereIn('id',$topicId)
            ->update(['c_message'=>0,'u_message'=>0]);
        return $topicData;
        try {
            DB::beginTransaction();

            $topUpdate = DB::table($topicModel->getTable())->whereIn('id',$topicId)
                ->update(['c_message'=>0,'u_message'=>0]);
            if (!$topUpdate){
                DB::rollBack();
                return false;
            }

            if (isset($usefulId)){
                $comUpdate = DB::table($UsefulModel->getTable())->whereIn('topic_id',$topicId)
                ->update(['unread'=>0]);
                if (!$comUpdate){
                    DB::rollBack();
                    return false;
                }
            }

            if (isset($commId)){
                $useUpdate = DB::table($CommentModel->getTable())->whereIn('topic_id',$topicId)
                    ->update(['unread'=>0]);
                if (!$useUpdate){
                    DB::rollBack();
                    return false;
                }
            }


            DB::commit();
            return $topicData;
        } catch (\Exception $exception) {
            DB::rollBack();
            \Log::error($exception);
            return false;
        }


    }

}
